try:
    from PyQt5.QtGui import *
    from PyQt5.QtCore import *
    from PyQt5.QtWidgets import *
except ImportError:
    from PyQt4.QtGui import *
    from PyQt4.QtCore import *

import time
import datetime
import json
import cv2
import numpy as np
import _thread

from libs.utils import newIcon

BB = QDialogButtonBox

def inferenceThread(threadName, txt):
    mv.make(txt)  
    showImg(txt)

class Worker(QThread):
    progressBarValue = pyqtSignal(int)
    listValue = pyqtSignal(str)
    endsignal = pyqtSignal(int, str)
    handle = 0
    
    def __init__(self, mvm, mTextList, style, save_dir, mainThread):
        super(Worker, self).__init__()
        self.mvm = mvm
        self.mTextList = mTextList
        self.setStackSize(1024*1024)
        self.style = style
        self.default_save_dir = save_dir
        self.running = False
        
    def run(self):
        self.running = False
        try:
            for index, text in enumerate(self.mTextList):
                self.listValue.emit(text)
                for i in range(10000):
                    if self.handle == 0:                      
                        if self.running:
                            # print("only print")
                            self.progressBarValue.emit(min(index * 90 + i, index * 90 + 90))
                            time.sleep(1)
                            if not self.running:
                                break
                        else:   
                            self.running = True
                            _thread.start_new_thread(self.inferenceThread, ("thread draw", text))
                                
                self.progressBarValue.emit(index * 90 + 90)
            self.endsignal.emit(0, "readAll")
            self.exec()
        except Exception as e:
            print(e)
            raise
        
    def inferenceThread(self, threadName, text):
        try:
            self.idict = self.mvm.singleText(text, self.style, self.default_save_dir) 
        except Exception as e:
            print(e)
            raise
        else:
            # print("else")
            self.mvm.readAndSave(self.idict, text=text, savedPath=self.default_save_dir)
        self.running = False
        
class GenerateDialog(QDialog):
    def __init__(self, parent=None, mvm=None, mTextList=None, style=None, default_save_dir=None):
        super(GenerateDialog, self).__init__(parent)
        self.mvm = mvm
        self.mTextList=mTextList
        self.setFixedWidth(800)
        self.parent = parent
        self.pb = QProgressBar()
        self.pb.setRange(0, 90 * len(self.mTextList))
        self.pb.setValue(0)
        self.style=style
        self.default_save_dir=default_save_dir
        
        layout = QVBoxLayout()
        layout.addWidget(self.pb)
        self.listWidget = QListWidget(self)
        layout.addWidget(self.listWidget)
        
        self.buttonBox = bb = BB(BB.Ok | BB.Cancel, Qt.Horizontal, self)
        
        bb.button(BB.Ok).setIcon(newIcon('done'))
        bb.button(BB.Cancel).setIcon(newIcon('undo'))
        bb.accepted.connect(self.validate)
        bb.rejected.connect(self.reject)
        layout.addWidget(bb)
        bb.button(BB.Ok).setEnabled(False)
        
        self.setLayout(layout)
        
        self.setWindowModality(Qt.ApplicationModal)
        
        self.thread_1 = Worker(self.mvm, self.mTextList, self.style, self.default_save_dir, self.parent)
        self.thread_1.progressBarValue.connect(self.handleProgressBarSignal)
        self.thread_1.listValue.connect(self.handleListWidgetSingal)
        self.thread_1.endsignal.connect(self.handleEndsignalSignal)
        
        self.time_start = time.time()
        
    def handleProgressBarSignal(self, i):
        self.pb.setValue(i)
        self.setWindowTitle("Generating -- ")
        
    def handleListWidgetSingal(self, i):
        self.listWidget.addItem(i)
        titem = self.listWidget.item(self.listWidget.count() - 1)
        self.listWidget.scrollToItem(titem)
        
    def handleEndsignalSignal(self, i, str):
        if i == 0 and str == "readAll":
            self.buttonBox.button(BB.Ok).setEnabled(True)
            self.buttonBox.button(BB.Cancel).setEnabled(False)
            
    def reject(self):
        print("reject")
        self.thread_1.handle = -1
        self.thread_1.quit()
        while not self.thread_1.isFinished():
            pass
        self.accept()
        
    def validate(self):
        self.accept()
            
    def popUp(self):
        self.thread_1.start()
        return 1 if self.exec_() else None
    
    def closeEvent(self, event):
        print("close")
        self.reject()